﻿using System.Net;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace Devonline.Identity;

/// <summary>
/// 用户得到授权后对具体 Action 访问的权限控制过滤器
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizationFilter(AuthorizationService authorizationService) : Attribute, IAsyncAuthorizationFilter
{
    protected readonly AuthorizationService _authorizationService = authorizationService;

    /// <summary>
    /// 此处仅针对授权完成后, 判断用户是否有权限访问某个资源
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (context.HttpContext.User.Identity?.IsAuthenticated ?? false)
        {
            var result = await _authorizationService.AuthorizeAsync();
            if (result is not IStatusCodeActionResult || (result is IStatusCodeActionResult statusCodeActionResult && statusCodeActionResult.StatusCode != (int)HttpStatusCode.OK))
            {
                context.Result = result;
            }
        }
    }
}